import { AnyAction } from 'redux';
import Slider from '@/typings/slider';
import Lesson from '@/typings/lesson';
import * as TYPES from '../action-types';
import actions from '@/store/actions/profile';

export interface Lessons {
  loading: boolean,
  list: Lesson[],
  hasMore: boolean,
  offset: number,
  limit: number
}

export interface HomeState {
  currentCategory: string;
  sliders: Slider[];
  lessons: Lessons;
}

let initialState: HomeState = {
  currentCategory: 'all',//默认当前的分类是显示全部类型的课程
  sliders: [],
  lessons: {
    loading: false,
    list: [],
    //  hasMore: total > offset + limit
    // 后台  hasMore: total > offset + limit
    hasMore: true,
    offset: 0,
    limit: 5
  }
}

export default function (state: HomeState = initialState, action: AnyAction): HomeState {
  console.log(action, 'home的action数据=》')
  switch (action.type) {
    case TYPES.SET_CURRENT_CATEGORY://修改当前分类
      return { ...state, currentCategory: action.payload };
    case TYPES.GET_SLIDERS:
      return { ...state, sliders: action.payload.data };
    case TYPES.SET_LESSONS_LOADING:
      // return {
      //   ...state,
      //   lessons: {
      //     ...state.lessons,
      //     loading: action.payload
      //   }
      // }
      // immer的好处
      state.lessons.loading = action.payload;
      return state;
    case TYPES.SET_LESSONS:
      // return {
      //   ...state,
      //   lessons: {
      //     ...state.lessons,
      //     loading: false,
      //     hasMore: action.payload.hasMore,
      //     list: [
      //       ...state.lessons.list,
      //       ...action.payload.list
      //     ],
      //     offset: state.lessons.offset + action.payload.list.length
      //   }
      // }

      state.lessons.loading = false;
      state.lessons.hasMore = action.payload.hasMore;
      state.lessons.list = [...state.lessons.list, ...action.payload.list];
      state.lessons.offset = state.lessons.offset + action.payload.list.length;
      return state;
    case TYPES.REFRESH_LESSONS:
      // return {
      //   ...state,
      //   lessons: {
      //     ...state.lessons,
      //     loading: false,
      //     hasMore: action.payload.hasMore,
      //     list: action.payload.list,
      //     offset: action.payload.list.length||0,
      //     limit: action.payload.list.length
      //   }
      // }
      state.lessons.loading = false;
      state.lessons.hasMore = action.payload.hasMore;
      state.lessons.list = action.payload.list;
      // state.lessons.offset = action.payload.list.length;
      console.log(action.payload.list.length,'action.payload.list.length');
      state.lessons.offset = 0;
      return state;
    default:
      return state;
  }
}